package co.gov.igac.observatorio.beans.idea;

import co.gov.igac.observatorio.entidades.idea.Entidad;
import co.gov.igac.observatorio.beans.idea.util.JsfUtil;
import co.gov.igac.observatorio.beans.idea.util.PaginationHelper;
import co.gov.igac.observatorio.ejbs.idea.EntidadFacade;

import co.gov.igac.observatorio.entidades.propuesta.Soluciongeo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "entidadController")
@SessionScoped
public class EntidadController implements Serializable {

    private Entidad current;
    private DataModel items = null;
    @EJB
    private co.gov.igac.observatorio.ejbs.idea.EntidadFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Map<Integer, List<Soluciongeo>> solucionesMap;

    public EntidadController() {
    }

    public Entidad getSelected() {
        if (current == null) {
            current = new Entidad();
            selectedItemIndex = -1;
        }
        return current;
    }

    private EntidadFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Entidad) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Entidad();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EntidadCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Entidad) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EntidadUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Entidad) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EntidadDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public void eliminarServicio(int indice) {
        this.getSelected().getServiciowebList().remove(indice);
    }

    public void eliminarSIG(int indice) {
        this.getSelected().getSigList().remove(indice);
    }

    public Map<Integer, List<Soluciongeo>> getSolucionesMap() {

        solucionesMap = new HashMap<Integer, List<Soluciongeo>>();
        if (this.getSelected().getSoluciongeoList() != null) {
            for (Soluciongeo soluciongeo : this.getSelected().getSoluciongeoList()) {
                List<Soluciongeo> listaSolucion = solucionesMap.get(soluciongeo.getTipotecnologia().getIdTipoTecnologia());
                if (listaSolucion == null) {
                    listaSolucion = new ArrayList<Soluciongeo>();
                }
                listaSolucion.add(soluciongeo);
                solucionesMap.put(soluciongeo.getTipotecnologia().getIdTipoTecnologia(), listaSolucion);
            }
        }
        System.out.print("Se realizo proceso de MAP");
        System.out.print("Esta vacia? " + solucionesMap.isEmpty());
        return solucionesMap;
    }

    public void eliminarSolucion(Soluciongeo soluciongeo) {

        this.getSelected().getSoluciongeoList().remove(soluciongeo);

    }

    @FacesConverter(forClass = Entidad.class)
    public static class EntidadControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            EntidadController controller = (EntidadController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "entidadController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Entidad) {
                Entidad o = (Entidad) object;
                return getStringKey(o.getIdEntidad());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + EntidadController.class.getName());
            }
        }
    }
}
